package com.jason.order.conroller;

import com.jason.common.base.BaseController;
import com.jason.common.error.BusinessErrorEnum;
import com.jason.common.error.BusinessException;
import com.jason.common.vo.CommonReturnType;
import com.jason.order.model.OrderModel;
import com.jason.order.service.OrderService;
import com.jason.um.user.model.UserModel;
import com.jason.um.utils.SpringSessionManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/order")
@Api(value = "api接口", description = "交易相关操作")
public class OrderController extends BaseController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private SpringSessionManager sessionManager;

    @PutMapping("/shop")
    @ApiOperation(value = "商品下单", notes = "根据商品ID和数量下单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "商品ID", required = true, paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "amount", value = "下单数量", required = true,  paramType = "query", dataType = "Integer")
    })
    public CommonReturnType buyItem(Integer id, Integer amount) throws BusinessException {

        if (id == null || amount == null){
            throw  new BusinessException(BusinessErrorEnum.PARAM_ILLEGAL_ERROR);
        }
        OrderModel orderModel = new OrderModel();
        orderModel.setAmount(amount);
        orderModel.setItemId(id);
        UserModel userModel = sessionManager.getLoginInfo();
        if (userModel == null) {
            throw new BusinessException(BusinessErrorEnum.USER_NOT_AUTH);
        }
        orderModel.setUserId(userModel.getId());
        Boolean success = orderService.buyItem(orderModel);
        if (success){
            return CommonReturnType.success("下单成功");
        } else {
            return CommonReturnType.fail("下单失败，未知错误");
        }
    }


}
